{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "class Company(object):\n",
    "    def __init__(self, employee_list):\n",
    "        self.employee = employee_list\n",
    "        \n",
    "    def __len__(self):\n",
    "        return len(self.employee)\n",
    "\n",
    "com = Company(['bobby1', 'bobby2'])\n",
    "print(hasattr(com, \"__len__\"))\n",
    "print(len(com))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "## 抽象基类\n",
    "## 使用：\n",
    "## 1、在某些情况下希望判定某个对象的类型\n",
    "from collections.abc import Sized\n",
    "print(isinstance(com, Sized))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 2、我们需要强制某个子类必须实现某个方法\n",
    "## 比如：实现一个web框架，继承cache（file，redis，memcached）\n",
    "## 需要设计一个抽象基类，指定子类必须实现某些方法\n",
    "class CacheBase():\n",
    "    def get(self, key):\n",
    "        raise NotImplementError\n",
    "    def set(self, key, value):\n",
    "        raise NotImplementError\n",
    "    \n",
    "class RedisCache(CacheBase):\n",
    "    def set(self, key, value):\n",
    "        pass\n",
    "\n",
    "redis_cache = RedisCache()\n",
    "redis_cache.set('key', 'value')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 模拟一个抽象基类\n",
    "import abc\n",
    "class CacheBase(metaclass=abc.ABCMeta):\n",
    "    @abc.abstractmethod\n",
    "    def get(self, key):\n",
    "        pass\n",
    "    \n",
    "    @abc.abstractmethod\n",
    "    def set(self, key, value):\n",
    "        pass\n",
    "\n",
    "class RedisCache(CacheBase):\n",
    "    pass\n",
    "\n",
    "redis_cache = RedisCache()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
